#pragma once

#include <QAbstractVideoSurface>
#include <QWidget>

class QCamera;
class QCameraImageCapture;
class QGraphicsView;
class QGraphicsScene;
class QGraphicsPixmapItem;
class QPaintEvent;

class FrameGrabber : public QAbstractVideoSurface {
    Q_OBJECT
public:
    FrameGrabber(QObject* parent = nullptr);

    bool present(const QVideoFrame& frame) override;

    QList<QVideoFrame::PixelFormat> supportedPixelFormats(
        QAbstractVideoBuffer::HandleType handleType = QAbstractVideoBuffer::NoHandle) const override;
signals:
    void frameAvailable(const QImage& image);
};

class CameraWidget : public QWidget {
    Q_OBJECT
public:
    CameraWidget(QWidget* parent = nullptr);
    bool isOpened();
    void open(QString dev);
    void close();
    QString getDevPath();

public slots:
    void setMirrored(bool enable);

private:
    void setErrorMessage(const QString& message);

protected:
    void paintEvent(QPaintEvent* event) override;

private:
    QCamera* m_camera = nullptr;
    QString m_errorMessage, m_dev;
    QCameraImageCapture* m_imageCapture;

    QGraphicsView* graphicsView;
    QGraphicsScene* graphicsScene;
    QGraphicsPixmapItem* pixmapItem;
    FrameGrabber* frameGrabber; // 用于拦截视频帧
};
